<template>
    <a-modal :footer="null" v-model:visible="visible" title="付款" @cancel="() => { emits('cancel') }">
        <p class=" mb-1"><span class=" font-semibold mr-2">商品订单:</span>{{ orderInfo.trade_no }}</p>
        <p class=" mb-1"><span class=" font-semibold mr-2">商品描述:</span>{{ orderInfo.product_name }}</p>
        <p class=" mb-1">
            <span class=" font-semibold mr-2">支付金额:</span>
            <span class=" text-4xl text-default">￥{{ (orderInfo.price / 100).toFixed(2) }}</span>
        </p>
        <div class="flex text-center mx-8">
            <div class=" w-[200px]">
                <qrcode-vue class=" mt-4 block mx-auto" :value="orderInfo.code_url" :size="200" />
                <p class=" bg-[#00c800] text-white my-1 mt-2 text-center">
                    {{ isDone ? "支付已完成！" : "请打开手机扫一扫完成支付!" }}
                </p>
            </div>
            <img src="@/assets/ep_sys_wx_tip.jpg">
        </div>
    </a-modal>
</template>

<script lang='ts' setup>
import { getPaystatus, getTradesInfo } from '@/request/api';
import qrcodeVue from 'qrcode.vue';
const router = useRouter()
let visible = ref<boolean>(false)
let isDone = ref<boolean>(false)
const props = withDefaults(defineProps<{
    trade_no: string,
    show: boolean
}>(), {
    trade_no: '',
    show: false
})
const emits = defineEmits(['cancel'])
let orderInfo = reactive({
    trade_no: '',
    price: 0,
    product_name: '',
    code_url: ''
})

let timer: NodeJS.Timer
let timerCount = ref<number>(0)
watchEffect(() => {
    visible.value = props.show
    if (props.show) {
        getTradesInfo({ code: props.trade_no }).then(res => {
            if (res.code == 200) {
                timer = setInterval(() => {
                    timerCount.value += 10000
                    if (timerCount.value > 1000 * 60 * 10) {
                        clearInterval(timer)
                        emits('cancel')
                    }
                    getStatus()
                }, 2000)
                orderInfo = Object.assign(orderInfo, JSON.parse(JSON.stringify(res.result)))
            }
        })
    } else {
        clearInterval(timer)
    }
})
const getStatus = () => {
    getPaystatus({ trade_no: props.trade_no }).then(res => {
        if (res.code == 200) {
            isDone.value = res.result.done
            if (isDone.value) {
                clearInterval(timer)
                timerCount.value = 5
                timer = setInterval(() => {
                    timerCount.value -= 1
                    if (timerCount.value <= 0) {
                        clearInterval(timer)
                        router.push({ name: 'create' })
                    }
                }, 1000)
            }
        }
    })
}
</script>